#include "loginrequest.h"

LoginRequest::LoginRequest(QObject *parent)
    : ExecutionObjectInterface(parent)
{
    urlPath_ = "http://pcw-textinclass.appspot.com/loginClient";

    username_ = "";
    password_ = "";

    manager_ = NULL;
}

LoginRequest::LoginRequest(QString username, QString password, QObject *parent)
    : ExecutionObjectInterface(parent)
{
    urlPath_ = "http://pcw-textinclass.appspot.com/loginClient";

    username_ = username;
    password_ = password;

    manager_ = NULL;
}

LoginRequest::~LoginRequest()
{

}

void LoginRequest::doInBackground()
{
    manager_ = new QNetworkAccessManager(this);

    if (manager_ == NULL) {
        emit error("Unable to allocate Network Access Manager");
        emit processFinished();
        return;
    }

    QUrl url(urlPath_);
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-www-form-urlencoded"));

    QByteArray data;
    QUrl params;

    params.addEncodedQueryItem("username", QUrl::toPercentEncoding(username_));
    params.addEncodedQueryItem("password", QUrl::toPercentEncoding(password_));

    data.append(params.toString().mid(1));

    connect(manager_, SIGNAL(finished(QNetworkReply*)), this, SLOT(onNetworkReply(QNetworkReply*)));

    manager_->post(request, data);
}

void LoginRequest::onPostExecute()
{
    emit objectFinished();
}

void LoginRequest::onNetworkReply(QNetworkReply *reply)
{
    QString response(reply->readAll());

    if (response == "Success") {

        QNetworkCookieJar *cookieJar = manager_->cookieJar();

        QList<QNetworkCookie> cookies = cookieJar->cookiesForUrl(QUrl(urlPath_));

        for (int i = 0; i < cookies.size(); i++) {
            QNetworkCookie cookie = cookies.at(i);

            QString cookieValue(cookie.toRawForm(QNetworkCookie::NameAndValueOnly));

            qDebug() << "Here...";

            emit responseStrings(response, cookieValue);
        }
    }
    else {
        emit responseStrings(response, "");
    }

    emit processFinished();
}

